﻿
#region Using Directives.

using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using RWXMLEdit.Common;

#endregion

namespace RWXMLEdit.Client.Forms
{
    public partial class FormEditUicCargoNumbers : Form
    {
        private XDocument _xDocument;
        private readonly string _railWorksPath;
        private string _currentCsvFilePath = string.Empty;
        private const string MsgBoxName = "RailWorks XML Editor Message";

        public FormEditUicCargoNumbers(XDocument xdoc, string railworkspath)
        {
            InitializeComponent();

            Text = "Edit UIC Standard Cargo Waggon Number";

            _xDocument = xdoc;
            _railWorksPath = railworkspath;

            Init();
        }

        #region Properties.

        [Localizable(false)]
        public override sealed string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        public XDocument GetXDocument
        {
            get { return _xDocument; }
        }

        #endregion

        #region Private Methods.

        private void Init()
        {
            string railWorksPath = GetProviderAndProduct();

            //WaggonTypeCode wtc = new WaggonTypeCode();

            if(string.IsNullOrEmpty(railWorksPath))
            {
                grbEdit.Enabled = false;
                grbPreview.Enabled = false;
                lvwWaggonNumber.Enabled = false;
                btnOK.Enabled = false;
                return;
            }
                
            _currentCsvFilePath = GetCsvFilePath(railWorksPath);

            if(string.IsNullOrEmpty(_currentCsvFilePath))
            {
                _currentCsvFilePath = CreateCsvFile(railWorksPath);
            }
            
            cboUicCountryCode.Items.AddRange(WaggonNumberHelper.GetWaggonUicCountryCode().ToArray());

            if (cboUicCountryCode.Items.Count > 0)
            {
                cboUicCountryCode.Items.Insert(0, "<Select Country Code>");
                cboUicCountryCode.SelectedIndex = 0;
            }
            else
            {
                cboUicCountryCode.Enabled = false;
                chkUicCountryCode.Enabled = false;
            }

            cboTypeCode.Items.AddRange(WaggonNumberHelper.GetWaggonTypeCode().ToArray());

            if (cboTypeCode.Items.Count > 0)
            {
                cboTypeCode.Items.Insert(0, "<Select Type Code>");
                cboTypeCode.SelectedIndex = 0;
            }
            else
            {
                cboTypeCode.Enabled = false;
                chkTypeCode.Enabled = false;
            }
        }

        #endregion

        #region Open And Create CSV-file.

        private string CreateCsvFile(string csvPath)
        {
            string path = string.Empty;

            string message = string.Format("There no CSV-file for waggon numbers\n\nWould you like to create a new file?");

            DialogResult dlgResult = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dlgResult == DialogResult.Yes)
            {
                saveFileDialog.InitialDirectory = _railWorksPath;
                saveFileDialog.FileName = string.Format("{0}.csv", "waggonnumber");
                saveFileDialog.Title = @"Create CSV File";

                DialogResult save = saveFileDialog.ShowDialog(this);

                if (save == DialogResult.OK)
                {
                    path = saveFileDialog.FileName;

                    TextWriter tw = new StreamWriter(path);

                    tw.WriteLine("0,0");

                    tw.Close();

                    SaveNewPathToXml(path, "NumberingList", csvPath);
                }
            }

            return path;
        }

        private void SaveNewPathToXml(string path, string attribute, string csvPath)
        {
            XElement doc = XElement.Load(_xDocument.CreateReader());

            XElement element = (from x in doc.DescendantsAndSelf()
                                where (string)x.Attribute("name") == attribute
                                select x).SingleOrDefault();

            if (element != null)
            {
                XElement element1 = (from x in element.Descendants()
                                     where (string)x.Attribute("name") == "CsvFile"
                                     let xElement = x.Element("cDeltaString")
                                     where xElement != null
                                     let xElement1 = xElement.Element("Element")
                                     where xElement1 != null
                                     select xElement1.Element("Value")).Single();

                if(path.Contains(csvPath))
                {
                    path = path.Replace(csvPath, "");

                    if (path.StartsWith("\\"))
                    {
                        path = path.Remove(0, 1);
                    }
                }

                element1.Value = path;

                _xDocument = XDocument.Load(doc.CreateReader(), LoadOptions.PreserveWhitespace);
            }
        }

        private string GetProviderAndProduct()
        {
            string path = string.Empty;

            XElement doc = XElement.Load(_xDocument.CreateReader());

            XElement element = (from x in doc.DescendantsAndSelf()
                                where (string)x.Attribute("name") == "PrimaryNamedTextureSet"
                                select x).SingleOrDefault();

            if (element != null)
            {
                string provider = (from x in element.Descendants()
                                   where (string)x.Attribute("name") == "Provider"
                                   let element2 = x.Element("cDeltaString")
                                   where element2 != null
                                   let xElement2 = element2.Element("Element")
                                   where xElement2 != null
                                   let element3 = xElement2.Element("Value")
                                   where element3 != null
                                   select element3.Value).ElementAt(0);

                string product = (from x in element.Descendants()
                                  where (string)x.Attribute("name") == "Product"
                                  let xElement = x.Element("cDeltaString")
                                  where xElement != null
                                  let xElement1 = xElement.Element("Element")
                                  where xElement1 != null
                                  let element1 = xElement1.Element("Value")
                                  where element1 != null
                                  select element1.Value).ElementAt(0);

                if(string.IsNullOrEmpty(provider) || string.IsNullOrEmpty(provider))
                {
                    path = string.Empty;
                }
                else
                {
                    path = Path.Combine(_railWorksPath, "Source", provider, product);
                    
                }
            }

            return path;
        }

        private string GetCsvFilePath(string railWorksPath)
        {
            string path = string.Empty;
            //csvPath = string.Empty;

            XElement doc = XElement.Load(_xDocument.CreateReader());

            XElement element = (from x in doc.DescendantsAndSelf()
                                where (string)x.Attribute("name") == "NumberingList"
                                select x).SingleOrDefault();
            if(element !=null)
            {
                string temp = (from x in element.Descendants()
                                    where (string)x.Attribute("name") == "CsvFile"
                               let xElement = x.Element("cDeltaString")
                               where xElement != null
                               let xElement1 = xElement.Element("Element")
                               where xElement1 != null
                               let element1 = xElement1.Element("Value")
                               where element1 != null
                               select element1.Value).ElementAt(0);

                if (string.IsNullOrEmpty(temp))
                {
                    path = string.Empty;
                }
                else
                {
                    path = Path.Combine(railWorksPath, temp);
                }
            }

            return path;
        }

        #endregion

        private void cboTypeCode_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if(cboTypeCode.SelectedIndex > 0)
            {
                WaggonTypeCode wtc = (WaggonTypeCode)cboTypeCode.SelectedItem;

                tlbTypeCode.Text = string.Format("{0:0#}", wtc.Number);
                tlbRiv.Text = wtc.Riv;
            }
            else
            {
                tlbTypeCode.Text = string.Empty;
                tlbRiv.Text = string.Empty;
            }
        }

        private void cboUicCountryCode_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (cboUicCountryCode.SelectedIndex > 0)
            {
                WaggonUicCountryCode wucc = (WaggonUicCountryCode)cboUicCountryCode.SelectedItem;

                tlbUicCountryCode.Text = string.Format("{0:0#}", wucc.NumericalCode);
                tlbOwner.Text = wucc.CompanyCode;
            }
            else
            {
                tlbUicCountryCode.Text = string.Empty;
                tlbOwner.Text = string.Empty;
            }
        }
    }
}
